<?php

namespace app\admin\controller\depot;

// 引入基类控制器
use app\common\controller\Backend;

// 入库
class Storage extends Backend
{
  // 供应商模型
  protected $SupplierModel = null;

  // 商品模型
  protected $ProductModel = null;

  // 入库商品模型
  protected $DepotProductModel = null;

  // 退货模型
  protected $BackModel = null;

  public function __construct()
  {
    parent::__construct();

    $this->model = model('Depot.Storage.Storage');
    $this->SupplierModel = model('Depot.Supplier');
    $this->ProductModel = model('Product.Product');
    $this->DepotProductModel = model('Depot.Storage.Product');
    $this->BackModel = model('Depot.Back.Back');

    $this->view->assign("typeList", $this->model->getTypeList());
    $this->view->assign("statusList", $this->model->getStatusList());
  }

  public function index()
  {
    if ($this->request->isAjax()) {
      // 过滤请求参数中的html标签和取消两边你空白
      $this->request->filter(['strip_tags', 'trim']);
      // 获取查询参数
      list($where, $sort, $order, $offset, $limit) = $this->buildparams();

      $total = $this->model
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->count();

      $list = $this->model
        ->with(['supplier'])
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();

      $result = [
        'rows' => $list,
        'total' => $total
      ];

      return json($result);
    }

    return $this->view->fetch();
  }
  // 入库
  public function add()
  {
    if ($this->request->isPost()) {
      $params = $this->request->param('row/a');
      $productList = json_decode($params['product'], true);

      $total = 0;

      // 商品数据
      $productData = [];

      foreach ($productList as $item) {
        $productData[] = [
          // 'storageid' => $this->model->id,
          'proid' => $item['id'],
          'nums'  => $item['nums'],
          'price' => $item['price'],
          'total' => $item['total'],
        ];

        $total += $item['total'];
      }

      $storageData = [
        'code'       => build_code('SU'), // 订单前缀可以自定义
        'supplierid' => $params['supplierid'],
        'type'       => $params['type'],
        'amount'     => $total,
        'remark'     => $params['remark'],
        'status'     => 0
      ];

      $this->model->startTrans();
      $this->DepotProductModel->startTrans();

      // 插入入库表
      $storageRes = $this->model->validate('common/Depot/storage/Storage')->save($storageData);

      if ($storageRes === false) {
        $this->error($this->model->getError());
        exit;
      }

      foreach ($productData as $k => $v) {
        $productData[$k]['storageid'] = $this->model->id;
      }

      // 插入商品数据
      $productRes = $this->DepotProductModel->validate('common/Depot/storage/Product')->saveAll($productData);

      if ($productRes === false) {
        $this->model->rollback();
        $this->error($this->DepotProductModel->getError());
        exit;
      }

      if ($storageRes === false || $productRes === false) {
        $this->model->rollback();
        $this->DepotProductModel->rollback();
        $this->error('添加失败');
        exit;
      } else {
        $this->model->commit();
        $this->DepotProductModel->commit();
        $this->success();
      }
    }

    return $this->view->fetch();
  }
  // 编辑入库
  public function edit($ids = NULL)
  {
    $row = $this->model->get($ids);

    // 找不到数据返回错误信息
    if (!$row) {
      $this->error(__('该入库单不存在，请重新选择'));
    }

    $supplier = $this->SupplierModel->where('id', $row['supplierid'])->find();

    if ($supplier) {

      if (!$supplier) {
        $this->error(__('该供应商不存在，请重新选择'));
      }
    } else {
      // 查询退货订单信息
      $back = $this->BackModel->with(['business'])->where(['storageid' => $row['id']])->find();

      if (!$back) {
        $this->error('退货单不存在');
      }
    }

    $productList = $this->DepotProductModel->where('storageid', $row['id'])->select();

    if (!$productList) {
      $this->error(__('该商品不存在，请重新选择'));
    }

    if ($this->request->isPost()) {
      $params = $this->request->param('row/a');
      $productArr = json_decode($params['product'], true);
      $delProIds = json_decode($params['delproid'], true);

      // myPrinf($params, $productArr, $delProIds);exit;

      // 开启事务
      $this->model->startTrans();
      $this->DepotProductModel->startTrans();

      $total = 0;

      // 存放封装好的商品数据
      $ProductData = [];

      // 封装一个在修改时新增的商品
      $NewProData = [];

      foreach ($productArr as $item) {
        if (isset($item['pid'])) {
          $ProductData[] = [
            'id' => $item['pid'],
            'proid' => $item['id'],
            'nums' => $item['nums'],
            'price' => $item['price'],
            'total' => $item['total'],
          ];
        } else {
          $NewProData[] = [
            'storageid' => $row['id'],
            'proid' => $item['id'],
            'nums' => $item['nums'],
            'price' => $item['price'],
            'total' => $item['total'],
          ];
        }
        $total += $item['total'];
      }

      // 封装入库数据
      $storageData = [
        'id' => $row['id'],
        'type' => $params['type'],
        'amount' => $total,
        'remark' => $params['remark'],
        'status' => $row['status'],
      ];

      if ($row['type'] == 1) {
        $storageData['supplierid'] = $params['supplierid'];
      }
      // 如果等于true说明直销入库
      if ($supplier) {
        $storageRes = $this->model->validate('common/Depot/storage/Storage.edit')->isUpdate(true)->save($storageData);
      } else {
        $storageRes = $this->model->validate('common/Depot/storage/Storage.back_edit')->isUpdate(true)->save($storageData);
      }

      if ($storageRes === false) {
        $this->error($this->model->getError());
        exit;
      }

      // 删除不需要的商品
      if (!empty($delProIds)) {
        $DelRes = $this->DepotProductModel->destroy($delProIds);

        if ($DelRes === false) {
          $this->model->rollback();
          $this->error($this->DepotProductModel->getError());
        }
      }

      $NewProRes = $this->DepotProductModel->validate('common/Depot/storage/Product')->saveAll($NewProData);

      // 验证数据
      $ProductRes = $this->DepotProductModel->validate('common/Depot/storage/Product.edit')->isUpdate(true)->saveAll($ProductData);

      if ($ProductRes === false || $NewProRes === false) {
        $this->model->rollback();
        $this->error($this->DepotProductModel->getError());
      }

      // 大判断
      if ($ProductRes === false || $storageRes === false || $NewProRes === false) {
        $this->model->rollback();
        $this->DepotProductModel->rollback();
        $this->error(__('修改失败'));
      } else {
        $this->model->commit();
        $this->DepotProductModel->commit();
        $this->success();
      }
    }


    // 商品的数据
    $productData = [];

    foreach ($productList as $item) {
      $product = model('Product.Product')->with(['type', 'unit'])->find($item['proid']);

      $productData[] = [
        'id'      => $item['id'],
        'price'   => $item['price'],
        'nums'    => $item['nums'],
        'total'   => $item['total'],
        'product' => $product
      ];;
    }

    // 赋值
    $data = [
      'row'      => $row,
      'supplier' => $supplier
    ];

    // 如果等于false说明这个退货入库
    if (!$supplier) {
      $data['back'] = $back;
    }

    // 返回js使用的数据
    $this->assignconfig('Product', ['productData' => $productData]);

    return $this->view->fetch('', $data);
  }
  // 软删除
  public function del($ids = null)
  {
    if ($this->request->isAjax()) {
      $row = $this->model->where(['id' => ['in', $ids]])->select();

      if (empty($row)) {
        $this->error(__('请选择需要删除入库单'));
      }

      $result = $this->model->destroy($ids);

      if ($result === false) {
        $this->error(__('删除入库单失败'));
      } else {
        $this->success();
      }
    }
  }
  // 入库审核
  public function process()
  {
    if ($this->request->isAjax()) {
      $id = $this->request->param('ids');

      $status = $this->request->param('status');

      $data = [];

      if ($status == 1) {
        $data = [
          'id' => $id,
          'status' => 2,
          'reviewerid' => $this->auth->id
        ];
      } else {
        $data = [
          'id' => $id,
          'status' => 1,
          'reviewerid' => $this->auth->id
        ];
      }

      $result = $this->model->isUpdate(true)->save($data);

      if ($result === FALSE) {
        $this->error();
      } else {
        $this->success();
      }
    }
  }
  // 撤销审核
  public function cancel($ids = null)
  {
    if ($this->request->isAjax()) {
      $row = $this->model->get($ids);

      if (!$row) {
        $this->error(__('该入库不存在，请重新选择'));
      }

      $data = [
        'id' => $row['id'],
        'status' => 0,
        'reviewerid' => $this->auth->id
      ];


      $result = $this->model->isUpdate(true)->save($data);

      if ($result === FALSE) {
        $this->error(__('撤销审核失败'));
      } else {
        $this->success(__('撤销审核成功'));
      }
    }
  }
  // 确认入库
  public function storage()
  {
    if ($this->request->isAjax()) {
      $id = $this->request->param('ids');

      $productList = $this->DepotProductModel->where('storageid', $id)->select();

      $ProductModel = model('Product.Product');

      // 开启事务
      $this->model->startTrans();
      $ProductModel->startTrans();

      // 更新入库表的数据
      $data = [
        'id' => $id,
        'status' => 3,
        'adminid' => $this->auth->id
      ];

      $result = $this->model->isUpdate(true)->save($data);

      if ($result === false) {
        $this->error($this->model->getError());
      }

      // 封装更新库存
      $productData = [];

      // 遍历商品
      foreach ($productList as $item) {
        $product = $ProductModel->find($item['proid']);

        if ($product['id'] == $item['proid']) {
          $productData[] = [
            'id' => $product['id'],
            'stock' => bcadd($product['stock'], $item['nums'])
          ];
        }
      }

      $productRes = $ProductModel->isUpdate(true)->saveAll($productData);

      if ($productRes === false) {
        $this->model->rollback();
        $this->error($ProductModel->getError());
      }

      if ($result === false || $productRes === false) {
        $this->model->rollback();
        $ProductModel->rollback();
        $this->error();
      } else {
        $this->model->commit();
        $ProductModel->commit();
        $this->success();
      }
    }
  }
  // 入库详情
  public function detail($ids = null)
  {
    // 入库数据
    $row = $this->model->with(['admin', 'reviewer'])->find($ids);
    // 供应商数据
    $supplier = $this->SupplierModel->where('id', $row['supplierid'])->find();
    // 入库商品数据
    $productList = $this->DepotProductModel->where('storageid', $row['id'])->select();
    // 商品数据
    $productData = [];

    foreach ($productList as $item) {
      // 查询每个商品信息
      $product = model('Product.Product')->with(['type', 'unit'])->find($item['proid']);

      $productData[] = [
        'id' => $item['id'],
        'price' => $item['price'],
        'nums' => $item['nums'],
        'total' => $item['total'],
        'product' => $product
      ];;
    }

    $data = [
      'row' => $row,
      'supplier' => $supplier,
      'productData' => $productData
    ];
    // 注入页面
    return $this->view->fetch('', $data);
  }
  // 查询供应商
  public function supplier()
  {
    // 设置过滤方法
    $this->request->filter(['strip_tags', 'trim']);

    if ($this->request->isAjax()) {
      if ($this->request->request('keyField')) {
        return $this->selectpage();
      }

      [$where, $sort, $order, $offset, $limit] = $this->buildparams();

      $total = $list = $this->SupplierModel
        ->where($where)
        ->count();

      $list = $this->SupplierModel
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();

      $result = [
        'total' => $total,
        'rows' => $list
      ];

      return json($result);
    }

    return $this->view->fetch();
  }
  // 查询商品
  public function product()
  {
    // 设置过滤方法
    $this->request->filter(['strip_tags', 'trim']);

    if ($this->request->isAjax()) {
      if ($this->request->request('keyField')) {
        return $this->selectpage();
      }

      [$where, $sort, $order, $offset, $limit] = $this->buildparams();

      $total = $list = $this->ProductModel
        ->where($where)
        ->count();

      $list = $this->ProductModel
        ->with(['type', 'unit'])
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();

      $result = [
        'total' => $total,
        'rows' => $list
      ];

      return json($result);
    }

    return $this->view->fetch();
  }
  // 回收站
  public function recyclebin()
  {
    if ($this->request->isAjax()) {
      if ($this->request->request('keyField')) {
        return $this->selectpage();
      }

      // 过滤请求参数中的html标签和取消两边你空白
      $this->request->filter(['strip_tags', 'trim']);
      // 获取查询参数
      list($where, $sort, $order, $offset, $limit) = $this->buildparams();


      $total = $this->model
        ->onlyTrashed()
        ->where($where)
        ->count();

      $list = $this->model
        ->onlyTrashed()
        ->with(['supplier'])
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();

      // var_dump($this->model->getLastSql());
      // exit;

      $result = [
        'rows' => $list,
        'total' => $total,
      ];

      return json($result);
    }

    return $this->view->fetch();
  }
  // 还原
  public function restore($ids = null)
  {
    $row = $this->model->onlyTrashed()->where(['id' => ['in', $ids]])->select();

    if (!$row) {
      $this->error(__('请选择需要还原记录'));
    }

    $result = $this->model->onlyTrashed()->where(['id' => ['in', $ids]])->update(['deletetime' => null]);

    if ($result != true) {
      $this->error(__('还原失败'));
    } else {
      $this->success();
    }
  }
  // 销毁
  public function destroy($ids = null)
  {
    if ($this->request->isAjax()) {
      $row = $this->model->onlyTrashed()->where(['id' => ['in', $ids]])->select();

      if (empty($row)) {
        $this->error(__('请选择需要销毁的记录'));
        exit;
      }

      $this->model->startTrans();
      $this->DepotProductModel->startTrans();

      $StorageProduct = $this->DepotProductModel->where(['storageid' => ['in', $ids]])->column('id');

      $storageRes = $this->model->destroy($ids, true);

      if ($storageRes === false) {
        $this->error($this->model->getError());
        exit;
      }

      $productRes = $this->DepotProductModel->destroy($StorageProduct);

      if ($productRes === false) {
        $this->model->rollback();
        $this->error($this->DepotProductModel->getError());
        exit;
      }

      if ($storageRes === false || $productRes === false) {
        $this->model->rollback();
        $this->DepotProductModel->rollback();
        $this->error(__('销毁失败'));
        exit;
      } else {
        $this->DepotProductModel->commit();
        $this->model->commit();
        $this->success('销毁成功');
        exit;
      }
    }
  }
}
